package com.stars.easyms.rest.handler;

import com.stars.easyms.rest.dto.EasyMsRestRequestEntity;
import org.springframework.core.NamedThreadLocal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>className: EasyMsRestSynchronizationManager</p>
 * <p>description: EasyMs的rest接口同步管理器</p>
 *
 * @author guoguifang
 * @date 2019-12-04 13:38
 * @since 1.4.2
 */
public final class EasyMsRestSynchronizationManager {

    private static final ThreadLocal<HttpServletRequest> HTTP_SERVLET_REQUEST_THREAD_LOCAL = new NamedThreadLocal<>("Current rest request");

    private static final ThreadLocal<HttpServletResponse> HTTP_SERVLET_RESPONSE_THREAD_LOCAL = new NamedThreadLocal<>("Current rest response");

    private static final ThreadLocal<EasyMsRestRequestEntity> REST_REQUEST_ENTITY_THREAD_LOCAL = new NamedThreadLocal<>("Current rest request entity");

    static void setRequestAndResponse(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                             EasyMsRestRequestEntity restRequest) {
        HTTP_SERVLET_REQUEST_THREAD_LOCAL.set(httpServletRequest);
        HTTP_SERVLET_RESPONSE_THREAD_LOCAL.set(httpServletResponse);
        REST_REQUEST_ENTITY_THREAD_LOCAL.set(restRequest);
    }

    public static HttpServletRequest getCurrentHttpServletRequest() {
        return HTTP_SERVLET_REQUEST_THREAD_LOCAL.get();
    }

    public static HttpServletResponse getCurrentHttpServletResponse() {
        return HTTP_SERVLET_RESPONSE_THREAD_LOCAL.get();
    }

    public static EasyMsRestRequestEntity getCurrentRestRequestEntity() {
        return REST_REQUEST_ENTITY_THREAD_LOCAL.get();
    }

    static void clear() {
        HTTP_SERVLET_REQUEST_THREAD_LOCAL.remove();
        HTTP_SERVLET_RESPONSE_THREAD_LOCAL.remove();
        REST_REQUEST_ENTITY_THREAD_LOCAL.remove();
    }

    private EasyMsRestSynchronizationManager() {}

}